/**
 * 
 */
package com.vector.ding.context;

import java.util.List;

import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;

import com.vector.ding.commons.util.spring.SpringUtil;
import com.vector.ding.dao.bean.MenuEntity;
import com.vector.ding.web.service.MenuService;

/**
 * Web相关的上下文，提供Web相关的变量获取
 * @author vector
 *
 */
public final class WebContext {
	
	/**
	 * Spring 应用上下文对象
	 */
	private static ApplicationContext applicationContext;
	
	/**
	 * Web Servlet上下文对象
	 */
	private static ServletContext servletContext;
	
	private static List<MenuEntity> menuEntities;
	
	/**
	 * @param applicationContext the applicationContext to set
	 */
	static void setApplicationContext(ApplicationContext applicationContext) {
		WebContext.applicationContext = applicationContext;
	}

	/**
	 * @param servletContext the servletContext to set
	 */
	static void setServletContext(ServletContext servletContext) {
		WebContext.servletContext = servletContext;
	}

	/**
	 * 获得Spring Application对象
	 * @return the applicationContext
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * 获得Web ServletContext对象
	 * @return the servletContext
	 */
	public static ServletContext getServletContext() {
		return servletContext;
	}
	
	/**
	 * 获得应用的跟路径，start with "/", but not end with "/", like "D:/path/server"
	 * @return
	 */
	public static String getAppRootPath() {
		String appRootPath = getServletContext().getRealPath("");
		if (appRootPath.endsWith("/"))
			appRootPath = appRootPath.substring(0, appRootPath.length() - 1);
		
		return appRootPath;
	}
	
	/**
	 * 获取web上下文路径，start with "/", but not end with "/", like "/server"
	 * @return
	 */
	public static String getContextPath() {
		return getServletContext().getContextPath();
	}
	
	public static List<MenuEntity> getMenuEntities() {
		if (menuEntities == null) {
			MenuService ms = SpringUtil.getBean(MenuService.class);
			menuEntities = ms.getMenuEntities(null);
		}
		
		return menuEntities;
	}
	
}
